package com.douwong.student.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.douwong.student.model.FiguresToDraw;
import com.douwong.student.popuwindow.ColorPickerPopuwindow;
import com.douwong.student.utils.DensityUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

public class PaletteView extends View {
	private Paint mPaint,cPaint,tPaint;
	private Path mPath;
	private Float mx,my;
	//bgBitmap发过来的图片  pBitmap画笔
	private Bitmap bgBitmap,pBitmap;
	private Canvas mCanvas;
	public boolean b_switch=false;
	//	public boolean p_switch=false;
	public boolean pen_mode=true;
	private List<FiguresToDraw> figures;
	private int width=0;
	private int height=0;
	private int bg_x,bg_y;
	private Context context;
	private int color;
	public boolean isDraw = false;
	private ColorPickerPopuwindow popu;
	private int currentStep = 0;

    public PaletteView(Context context) {
        this(context,null);
    }

    public PaletteView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public PaletteView(Context context, AttributeSet attrs) {
		this(context, attrs,0);
		// TODO Auto-generated constructor stub
		this.context=context;
		mPaint=new Paint();
        mPaint.setColor(Color.BLACK);
        mPaint.setStrokeWidth(getCoodinatePx(3));
        setPenAtribute(mPaint);
        cPaint=new Paint();
        cPaint.setStrokeWidth(getCoodinatePx(10)); 
        setPenAtribute(cPaint);            
        figures=new ArrayList<FiguresToDraw>();
        tPaint=new Paint();
        tPaint.setAlpha(0);
	}
    private void setPenAtribute(Paint paint){
    	paint.setAntiAlias(true);
    	paint.setDither(true);
    	paint.setStyle(Paint.Style.STROKE);
    	paint.setStrokeJoin(Paint.Join.ROUND);
    	paint.setStrokeCap(Paint.Cap.ROUND);
    	       
    }

	public void setPopuwindow(ColorPickerPopuwindow popu) {
		this.popu = popu;

	}
	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}

	private int size;

	public int getColor() {
		return color;
	}

	public void setColor(int color) {
		this.color = color;
	}

	//	private final String TAG="MyDrawView";
	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		
		Log.d("MyDrawView", "View onSizeChange:w:h:oldw:oldh  "+w+":"+h+":"+oldw+":"+oldh);
//		pBitmap=Bitmap.createBitmap(w, h, Config.ARGB_8888);		
		width=w;
		height=h;
//		setBitmap(tmpBitmap,false);
		initP_Canvas();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if(isDraw){
			if (popu.isShowing()) {
				popu.dismiss();
			}
			float x=event.getX();
			float y=event.getY();
			switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					mPath=new Path();
					mPath.moveTo(x, y);
					mx=x;
					my=y;
					invalidate();
					break;
				case MotionEvent.ACTION_MOVE:

					float dx= Math.abs(x-mx);
					float dy= Math.abs(y-my);
					if(dx>4||dy>4){
						mPath.quadTo(mx,my,(mx+x)/2,(my+y)/2);
						mx=x;
						my=y;
						if(!pen_mode){
							mCanvas.drawPath(mPath, cPaint);
						}
						invalidate();
					}
					break;
				case MotionEvent.ACTION_UP:
					mPath.lineTo(mx,my);
					if(pen_mode){
						mCanvas.drawPath(mPath, mPaint);
						figures.add(new FiguresToDraw(mPath, mPaint,true));
					}else{
						figures.add(new FiguresToDraw(mPath, cPaint,true));
						//					mCanvas.drawPath(mPath, cPaint);
						//					figures.add(new FiguresToDraw(mPath, cPaint));
					}
					currentStep = figures.size() - 1;
					invalidate();
					mPath=null;

					break;
			}


			return true;
		}
		return false;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		
		
		if(bgBitmap!=null){
			canvas.drawBitmap(bgBitmap, bg_x,bg_y, null);
		}		
		
	    if(mPath!=null){

		 if(pen_mode){
			canvas.drawPath(mPath, mPaint);
		 }else{
			canvas.drawPath(mPath, tPaint);
		  }		
	     }
	   if(pBitmap!=null){
			canvas.drawBitmap(pBitmap, 0,0, null);
		}
	}

    private Bitmap tmpBitmap=null;
    public void attachBGBackgoud(Bitmap mp){
		tmpBitmap=mp;
	}

	private void setBitmap(Bitmap mp, boolean ispcmark){
		//mw/mh 图片大小  width/height 屏幕大小


		if(!ispcmark){

			System.gc();

			int mw_t=mp.getWidth();
			int mh_t=mp.getHeight();


//		Log.i(TAG, "get picture size, width:height "+mw_t+", :"+mh_t);

			int mw=getCoodinatePx(mw_t);
			int mh=getCoodinatePx(mh_t);

//		Log.i(TAG, "trun size, width:height :W:h"+mw+", :"+mh+", :"+width+",: "+height);
			//图片的宽高均大于屏幕，缩小为屏幕等比宽高
			if(mw>width&&mh>height){
				bgBitmap= Bitmap.createBitmap(picZoom(mp, width, height));
				bg_x=0;
				bg_y=0;

				//图片宽高其中有一项大于屏幕时
			}else if(mw>width||mh>height){
				if(mw>width){
					bgBitmap= Bitmap.createBitmap(picZoom(mp, width, mh));
					bg_x=0;
					bg_y=(height-mh)/getCoodinatePx(2);

				}else{
					bgBitmap= Bitmap.createBitmap(picZoom(mp, mw, height));
					bg_x=(width-mw)/getCoodinatePx(2);
					bg_y=0;
				}
				//图片均小于屏幕时
			}else{

				int dw=(width*3)/5;
				int dh=(height*3)/5;

				if(mw<dw&&mh<dh){
					bgBitmap= Bitmap.createBitmap(picZoom(mp, dw, dh));
				}else{
					bgBitmap= Bitmap.createBitmap(picZoom(mp, mw, mh));
//			bgBitmap=mp;
				}
				int w=bgBitmap.getWidth();
				int h=bgBitmap.getHeight();

//		Log.i(TAG, "bitmap w and h:"+w+":"+h);

				bg_x=(width-w)/2;
				bg_y=(height-h)/2;
//		Log.i(TAG, "draw x and y:"+bg_x+":"+bg_y);
			}
		}else{
			bgBitmap= Bitmap.createBitmap(picZoom(mp, width, height));
//			bgBitmap=mp;
//			bg_x=(width-mp.getWidth())/2;
//			bg_y=(height-mp.getHeight())/2;
			bg_x=0;
			bg_y=0;
		}
		System.gc();
		invalidate();
	}
	
	public Bitmap getBitmap(){
		Bitmap bm= Bitmap.createBitmap(width,height, Config.ARGB_8888);
		Canvas cv=new Canvas(bm);
		cv.drawColor(Color.WHITE);
		if(bgBitmap!=null){
			cv.drawBitmap(bgBitmap, bg_x,bg_y, null);
		}
		
		if(pBitmap!=null){
			cv.drawBitmap(pBitmap, 0,0, null);
		}				
		return bm;	
	 }
	
	private int getCoodinatePx(int value){
		
		return DensityUtil.dip2px(context, value);
	}

     public void goBackOnce(){
    	 
         if(figures!=null&&figures.size()>0){
			 int removeindex=figures.size()-1;
			 backlist.add(figures.get(removeindex));
       	     figures.remove(removeindex);
         }        
         initP_Canvas();
         Iterator<FiguresToDraw> iterator=figures.iterator();
         while(iterator.hasNext()){
       FiguresToDraw p=iterator.next();
            mCanvas.drawPath(p.path, p.paint);        	
         }
         invalidate();
    	 
     }


	private Stack<FiguresToDraw> backlist=new Stack<FiguresToDraw>();

	public void next(){
		if(!backlist.isEmpty()){
            figures.add(backlist.peek());
			initP_Canvas();
			Iterator<FiguresToDraw> iterator=figures.iterator();
			while(iterator.hasNext()){
				FiguresToDraw p=iterator.next();
				mCanvas.drawPath(p.path, p.paint);
			}
			invalidate();
		}
	}
	public void undo(int steps) {
		try {
			 {
				 if(figures.size()==0){
					 return;
				 }
				if (steps == 1) {// 下一步
					if (figures.size() >= (currentStep + 1)) {
						figures.get(currentStep + 1).isVisible=true;
						currentStep = currentStep + 1;
					}
				} else if (steps == -1) {// 上一步
					Log.e("currentStep", currentStep + "");
					{
						figures.get(currentStep).isVisible=false;
						if (currentStep >= 0) {
							currentStep--;
						}
//						initP_Canvas();
//						Iterator<FiguresToDraw> iterator=figures.iterator();
//						while(iterator.hasNext()){
//							FiguresToDraw p=iterator.next();
//							if(p.isVisible){
//								mCanvas.drawPath(p.path, p.paint);
//							}
//						}

					}

				}
			}

			initP_Canvas();
			for(int i=0;i<figures.size();i++){
				FiguresToDraw p=figures.get(i);
				if(p.isVisible){
					mCanvas.drawPath(p.path, p.paint);
				}
			}
//			Iterator<FiguresToDraw> iterator=figures.iterator();
//			while(iterator.hasNext()){
//				FiguresToDraw p=iterator.next();
//				if(p.isVisible){
//					mCanvas.drawPath(p.path, p.paint);
//				}
//			}
			invalidate();
		} catch (IndexOutOfBoundsException e) {
			e.printStackTrace();
		}
	}
     public void clear(){
    	 
    	 if(figures!=null&&figures.size()>0){
     		figures.clear(); 
     	 }
		 currentStep=0;
//		 if(!backlist.isEmpty()){
//			 backlist.clear();
//		 }
    	 initP_Canvas();
     	 invalidate(); 
    	 
     }
     
     public void reclecyBitmap(){
    	 
    	 pBitmap.recycle();
    	 
    	 if(bgBitmap!=null){
    		bgBitmap.recycle(); 
    		bgBitmap=null;
    	 }    	 
    	 pBitmap=null;    	 
    	 mCanvas=null;
    	 figures=null;  
    	 
    	 System.gc();
     }
     
     
     //1 pen 2 erase
     public void changePenMode(int mode){
    	 
      switch(mode){
    	 case 1:
			 mPaint=new Paint();
			 setPenAtribute(mPaint);
			 pen_mode=true;
    		 mPaint.setStrokeWidth(this.size*2);
    		 mPaint.setColor(this.color);
    		 break;
    	 case 2:
			 cPaint=new Paint();
			 setPenAtribute(cPaint);
			 pen_mode=false;
    		 cPaint.setAlpha(0);
			 cPaint.setStrokeWidth(this.size*2);
    		 cPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    		 break;	 
    	 
    	 }
    	 
     }
     
     private void initP_Canvas(){

    	if(pBitmap!=null && !pBitmap.isRecycled()){
    		 pBitmap.recycle();
             pBitmap=null;
             System.gc();
    	} 	
    	 
     	pBitmap= Bitmap.createBitmap(width, height, Config.ARGB_8888);
    	
//     	Log.e("MyDrawView", "pBitmap instance: "+pBitmap);
     	
       if(mCanvas==null){
     		mCanvas=new Canvas(pBitmap);
     	}
       
         mCanvas.setBitmap(pBitmap);     	
     
     }
     
     
 	public Bitmap picZoom(Bitmap bmp, int dstWidth, int dstHeight) {
		int width = bmp.getWidth();
		int height = bmp.getHeight();		
		float scaleW = ((float) dstWidth) / width;
		float scaleH = ((float) dstHeight) / height;
		Matrix mt = new Matrix();
		mt.postScale(scaleW, scaleH);
		Bitmap bm = Bitmap.createBitmap(bmp, 0, 0, width, height, mt, true);
		return bm;
	}
     
     

	
	
	
	
}
